package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.clients.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.IndexService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private GoodsRepository goodsRepository;


//    private final ItemClient itemClient;
//    private GoodsRepository goodsRepository;
//    public IndexServiceImpl(ItemClient itemClient, GoodsRepository goodsRepository) {
//        this.itemClient = itemClient;
//        this.goodsRepository = goodsRepository;
//    }

    /**
     * 导入数据到es
     * 1.查询数据库数据（商品数据）,委托item-service，feign
     * 2.需要把拿到SpuDTO===>Goods
     */
    @Override
    public void loadData() {

        //先删除索引库
        try {
            this.goodsRepository.deleteIndex();
        } catch (Exception e) {
//            log.error("删除失败，可能索引库不存在！", e);
        }

        //创建索引库
        this.goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");


        int page = 1;
        while (true) {

            //分页查询所有数据
            PageDTO<SpuDTO> spuDTOPageDTO = this.itemClient.pageQuery(50, page++, null, null, true, null);
            Long totalPage = spuDTOPageDTO.getTotalPage();

            //防止数据库彻底是空的
            if (null == totalPage || 0 == totalPage) {
                throw new LyException(400, "数据导入出错，数据根本不存在");
            }


            List<Goods> goodsList = spuDTOPageDTO.getItems().stream().map(this::buildGoods).collect(Collectors.toList());
            this.goodsRepository.saveAll(goodsList);

            //数据查询结束，当前页是最后一页
            if (page > totalPage) {
                break;
            }

        }
    }

    @Override
    public Goods buildGoods(SpuDTO spuDTO) {
        Goods goods = new Goods();

        BeanUtils.copyProperties(spuDTO, goods);

        //categoryId
        goods.setCategoryId(spuDTO.getCid3());

        //updateTime
        goods.setUpdateTime(new Date());


        //分类，品牌，分类+品牌，品牌+分类，品牌+商品名称（spu.name）
        //suggestion
        List<String> suggs = new ArrayList<>();

        String brandName = StringUtils.substringBefore(spuDTO.getBrandName(), "（");

        String categoryName = spuDTO.getCategoryName().split("/")[2];

        suggs.add(categoryName);
        suggs.add(brandName);
        suggs.add(categoryName + brandName);
        suggs.add(brandName + categoryName);
        suggs.add(brandName + spuDTO.getName());

        goods.setSuggestion(suggs);


        //根据spuId查询对应的sku列表集合
        List<SkuDTO> skuDTOS = this.itemClient.listSkuBySpu(spuDTO.getId());

        if (CollectionUtils.isEmpty(skuDTOS)) {
            throw new LyException(400, "数据导入失败，给定的商品没有对应的sku");
        }
        Set<Long> prices = new HashSet<>();

        long sold = 0;
        for (SkuDTO skuDTO : skuDTOS) {
            prices.add(skuDTO.getPrice());
            sold += skuDTO.getSold();
        }

        //prices
        goods.setPrices(prices);

        //sold
        goods.setSold(sold);

        //image
        goods.setImage(StringUtils.substringBefore(skuDTOS.get(0).getImages(), ","));


        //specs,可搜索规格参数
        List<SpecParamDTO> specParam = this.itemClient.findSpecParamWithValueBySpu(spuDTO.getId(), true);

        List<Map<String, Object>> specResultList = new ArrayList<>();

        specParam.forEach(specParamDTO -> {
            Map<String, Object> paramMap = new HashMap<>();

            paramMap.put("name", specParamDTO.getName());

            //存储到es中要给非重要参数值划分区间
            paramMap.put("value", chooseSegment(specParamDTO));

            specResultList.add(paramMap);
        });
        goods.setSpecs(specResultList);

        return goods;
    }

    @Override
    public void addIndex(Long spuId) {

        PageDTO<SpuDTO> spuDTOPageDTO = this.itemClient.pageQuery(1, 1, null, null, true, spuId);

        List<SpuDTO> items = spuDTOPageDTO.getItems();
        if (!CollectionUtils.isEmpty(items)) {
            Goods goods = buildGoods(items.get(0));
            this.goodsRepository.save(goods);

        }
    }

    @Override
    public void deleteIndex(Long spuId) {

        this.goodsRepository.deleteById(spuId);
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }


}
